package com.wxl.common

import android.app.Activity
import android.app.Application
import android.text.TextUtils
import com.alibaba.fastjson.JSONObject
import com.wxl.common.bean.ConfigBean
import com.wxl.common.http.OkGoApi
import com.wxl.common.life.ActivityCallback
import com.wxl.common.util.SpUtil

/**
 * create file time : 2021/2/22
 * create user : wxl
 * subscribe :
 */
class AppContext private constructor() {

    private lateinit var context: Application
    private val activityCallback: ActivityCallback = ActivityCallback()
    private var config:ConfigBean? = null

    companion object {
        val appContext = AC.ac
    }

    private object AC {
        val ac = AppContext()
    }

    fun init(context: Application, debug: Boolean) {
        this.context = context
        SpUtil.context = context
        AppConstant.debug = debug
        OkGoApi.api.setBaseUrl(AppConstant.baseUrl, context)
        this.context.registerActivityLifecycleCallbacks(activityCallback)
    }

    fun getApplication(): Application {
        return context
    }


    fun getCurrentActivity(): Activity? {
        return activityCallback.getCurrentActivity()
    }

    fun isLogin(): Boolean {
        return TextUtils.isEmpty(SpUtil.sp.getString("userId")) || TextUtils.isEmpty(
            SpUtil.sp.getString(
                "token"
            )
        )
    }

    fun saveConfig(config: ConfigBean) {
        this.config = config
        SpUtil.sp.put("config", JSONObject.toJSONString(config))
    }


    fun saveMainHomeFirstData(data: String){
        SpUtil.sp.put("MainHomeFirstBean", data)
    }


    fun getMainHomeFirstData():String{
        return SpUtil.sp.getString("MainHomeFirstBean")
    }


    /**
     * 获得图片基础地址
     */
    fun getImgBaseUrl(): String {
        if(config != null){
            return config!!.url_cos
        } else {
            val configStr = SpUtil.sp.getString("config")
            if(!TextUtils.isEmpty(configStr)) {
                config = JSONObject.parseObject(configStr, ConfigBean::class.java)
            }
            if(config != null){
                return config!!.url_cos
            }
        }
        return ""
    }
}